import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/CV2/lesson/Day03'
img_name = 'gradient.png'
img_path1 = os.path.join(img_dir, img_name)

spr = 2
spc = 3
spn = 0
plt.figure(figsize=[9, 6])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_GRAYSCALE)
print('original shape', img.shape)
H, W = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', cmap='gray')

sep('threshold')
LOW, HIGH = 127, 255
ret, thresh1 = cv.threshold(img, LOW, HIGH, cv.THRESH_BINARY)
ret, thresh2 = cv.threshold(img, LOW, HIGH, cv.THRESH_BINARY_INV)
ret, thresh3 = cv.threshold(img, LOW, HIGH, cv.THRESH_TRUNC)
ret, thresh4 = cv.threshold(img, LOW, HIGH, cv.THRESH_TOZERO)
ret, thresh5 = cv.threshold(img, LOW, HIGH, cv.THRESH_TOZERO_INV)

th_imgs = [thresh1, thresh2, thresh3, thresh4, thresh5]
titles = ['bin', 'bin_inv', 'trunc', 'to0', 'to0_inv']
for th_img, title in zip(th_imgs, titles):
    my_show_img(th_img, title, cmap='gray')

plt.show()
